package team.nine.kuaichezuche.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import team.nine.kuaichezuche.model.VehicleInfo;
import team.nine.kuaichezuche.model.VehicleInstance;
import team.nine.kuaichezuche.service.VehicleInfoService;
import team.nine.kuaichezuche.service.VehicleInstanceService;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 编辑车辆信息控制器，处理前端提交的车辆信息更新请求
 */
@RestController
@RequestMapping("/api/vehicle")
public class EditVehicleController {

    @Autowired
    private VehicleInfoService vehicleInfoService;

    @Autowired
    private VehicleInstanceService vehicleInstanceService;

    // 日期格式化对象
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");

    /**
     * 处理前端提交的车辆信息更新请求
     * @param updateData 包含车辆信息更新数据的Map对象
     * @return 处理结果，包含成功或失败信息
     */
    @PutMapping("/update")
    public ResponseEntity<Map<String, Object>> updateVehicle(@RequestBody Map<String, Object> updateData) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 验证必要参数
            if (!updateData.containsKey("id") || !updateData.containsKey("instanceId")) {
                response.put("status", "error");
                response.put("code", 4000);
                response.put("message", "车辆ID和车辆实例ID不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            // 解析ID参数
            Integer vehicleInfoId = Integer.parseInt(updateData.get("id").toString());
            Integer vehicleInstanceId = Integer.parseInt(updateData.get("instanceId").toString());

            // 检查车辆信息和车辆实例是否存在
            VehicleInfo existingVehicleInfo = vehicleInfoService.getVehicleInfoById(vehicleInfoId);
            VehicleInstance existingVehicleInstance = vehicleInstanceService.getVehicleInstanceById(vehicleInstanceId);

            if (existingVehicleInfo == null) {
                response.put("status", "error");
                response.put("code", 4001);
                response.put("message", "车辆信息不存在，ID: " + vehicleInfoId);
                return ResponseEntity.badRequest().body(response);
            }

            if (existingVehicleInstance == null) {
                response.put("status", "error");
                response.put("code", 4002);
                response.put("message", "车辆实例不存在，ID: " + vehicleInstanceId);
                return ResponseEntity.badRequest().body(response);
            }

            // 更新车辆信息
            updateVehicleInfo(existingVehicleInfo, updateData);
            // 更新车辆实例信息
            updateVehicleInstance(existingVehicleInstance, updateData);

            // 保存更新后的信息
            VehicleInfo updatedVehicleInfo = vehicleInfoService.updateVehicleInfo(existingVehicleInfo);
            VehicleInstance updatedVehicleInstance = vehicleInstanceService.updateVehicleInstance(existingVehicleInstance);

            // 构造成功响应
            response.put("status", "success");
            response.put("code", 200);
            response.put("message", "车辆信息更新成功");
            response.put("vehicleInfoId", updatedVehicleInfo.getId());
            response.put("vehicleInstanceId", updatedVehicleInstance.getId());

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            // 捕获并处理异常
            response.put("status", "error");
            response.put("code", 500);
            response.put("message", "服务器错误: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 更新车辆信息
     */
    private void updateVehicleInfo(VehicleInfo vehicleInfo, Map<String, Object> updateData) {
        if (updateData.containsKey("brand")) {
            vehicleInfo.setBrand(updateData.get("brand").toString());
        }
        if (updateData.containsKey("model")) {
            vehicleInfo.setModel(updateData.get("model").toString());
        }
        if (updateData.containsKey("color")) {
            vehicleInfo.setColor(updateData.get("color").toString());
        }
        if (updateData.containsKey("seat_count")) {
            vehicleInfo.setSeatCount(Byte.parseByte(updateData.get("seat_count").toString()));
        }
        if (updateData.containsKey("power_type")) {
            String powerTypeStr = updateData.get("power_type").toString();
            try {
                // 兼容中文/英文、大小写
                VehicleInfo.PowerType powerType;
                try {
                    powerType = VehicleInfo.PowerType.valueOf(powerTypeStr);
                } catch (IllegalArgumentException e) {
                    // 尝试英文字段映射
                    if ("GASOLINE".equalsIgnoreCase(powerTypeStr) || "PETROL".equalsIgnoreCase(powerTypeStr)) powerType = VehicleInfo.PowerType.汽油;
                    else if ("DIESEL".equalsIgnoreCase(powerTypeStr)) powerType = VehicleInfo.PowerType.柴油;
                    else if ("ELECTRIC".equalsIgnoreCase(powerTypeStr)) powerType = VehicleInfo.PowerType.电动;
                    else if ("HYBRID".equalsIgnoreCase(powerTypeStr) || "HYBRID_ELECTRIC".equalsIgnoreCase(powerTypeStr)) powerType = VehicleInfo.PowerType.油电混动;
                    else throw e;
                }
                vehicleInfo.setPowerType(powerType);
            } catch (IllegalArgumentException e) {
                throw new IllegalArgumentException("无效的动力类型: " + powerTypeStr);
            }
        }
    }

    /**
     * 更新车辆实例信息
     */
    private void updateVehicleInstance(VehicleInstance vehicleInstance, Map<String, Object> updateData) throws ParseException {
        if (updateData.containsKey("license_plate")) {
            vehicleInstance.setLicensePlate(updateData.get("license_plate").toString());
        }
        if (updateData.containsKey("mileage")) {
            vehicleInstance.setMileage(Integer.parseInt(updateData.get("mileage").toString()));
        }
        if (updateData.containsKey("daily_rate")) {
            vehicleInstance.setDailyRate(new BigDecimal(updateData.get("daily_rate").toString()));
        }
        if (updateData.containsKey("available_start")) {
            vehicleInstance.setAvailableStart(parseDateFlexible(updateData.get("available_start")));
        }
        if (updateData.containsKey("available_end")) {
            vehicleInstance.setAvailableEnd(parseDateFlexible(updateData.get("available_end")));
        }
        if (updateData.containsKey("next_maintenance")) {
            vehicleInstance.setNextMaintenance(parseDateFlexible(updateData.get("next_maintenance")));
        }
        if (updateData.containsKey("insurance_info")) {
            vehicleInstance.setInsuranceInfo(updateData.get("insurance_info").toString());
        }
        if (updateData.containsKey("status")) {
            vehicleInstance.setStatus(Byte.parseByte(updateData.get("status").toString()));
        }
    }

    /**
     * 兼容不同来源的日期格式（字符串、时间戳、ISO8601）
     */
    private Date parseDateFlexible(Object source) throws ParseException {
        if (source == null) return null;
        if (source instanceof Date) return (Date) source;
        String s = source.toString();
        // 尝试时间戳（毫秒）
        try {
            if (s.matches("^\\d{10,13}$")) {
                long ts = Long.parseLong(s);
                if (s.length() == 10) ts = ts * 1000;
                return new Date(ts);
            }
        } catch (Exception ignored) {}
        // 尝试 ISO8601
        try {
            if (s.contains("T")) {
                return javax.xml.bind.DatatypeConverter.parseDateTime(s).getTime();
            }
        } catch (Exception ignored) {}
        // 回退到固定格式
        return DATE_FORMAT.parse(s);
    }
}